package com.demo.crm.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.arvato.crm.model.entity.Manager;
import com.demo.crm.model.UserToken;
import com.demo.crm.security.session.SessionRegistryImplExtend;
import com.demo.crm.service.LogService;
import com.demo.crm.service.ManagerService;

/**
 * 登录登出
 *
 * @author tanshuai
 */
@Controller
public class SignInOrOutController {

    @Autowired
    private ManagerService managerService;

    @Autowired
    private LogService logService;

    @Autowired
    private SessionRegistryImplExtend sessionRegistry;

    @RequestMapping("/login")
    public String login(String name, String password, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object o = managerService.login(name, password);
        if (!(o instanceof Manager)) {
            session.setAttribute("errorMsg", o);
            return "redirect:/login.jsp";
        }

        Manager manager = ((Manager) o);

        UserToken userToken = new UserToken();
        userToken.setUserKey(manager.getName());
        userToken.setPrincipal(manager);

//        List<Role> roles = manager.getRoles();
//        Set<String> authorities = new LinkedHashSet<>(roles.size());
//        for (Role role : roles) {
//            authorities.add(role.getName());
//        }
//        userToken.setAuthorities(authorities);

        session.setAttribute("userToken", userToken);
        sessionRegistry.register(userToken, session);

        logService.log("登录", name, request);
        return "redirect:/jsp/index.jsp";
    }

    @RequestMapping("/loginOut")
    public String login(HttpServletRequest request) {
        UserToken userToken = UserToken.getUserToken(request);

        String userName = null;
        if (userToken != null) {
            userName = userToken.getUserKey();
        }
        logService.log("退出", userName, request);

        request.getSession().invalidate();
        return "redirect:/login.jsp";
    }
}
